package com.csist.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.csist.pojo.po.basicInfoModule.EducationBackground;
import com.csist.pojo.po.basicInfoModule.LevelMajorInfo;
import com.csist.pojo.po.basicInfoModule.SpecificationMajorInfo;
import com.csist.service.po.basicInfoModule.SpecificationMajorInfoService;
import com.csist.service.po.basicInfoModule.impl.SpecificationMajorInfoServiceImpl;
import com.csist.util.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/specificationMajorInfo")
public class SpecificationMajorInfoServlet extends HttpServlet {
    private JSONObject jsonObject;
    private SpecificationMajorInfoService specificationMajorInfoService = new SpecificationMajorInfoServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //        这里如果request没有json字符串，则jsonObject为null（获取不到）
        jsonObject = JSONUtil.getJSONObject(request);
        if (jsonObject == null) {
            err(request, response);
            return;
        }
        String type = jsonObject.getString("type");
        if (type != null) {
            switch (type) {
                case "add":
                    add(request, response);
                    break;
                case "query":
                    show(request, response);
                    break;
                case "edit":
                    edit(request, response);
                    break;
                case "editByState":
                    editByState(request, response);
                    break;
                case "conditionalShow":
                    conditionalShow(request, response);
                    break;
                default:
                    err(request, response);
            }
        } else {
            err(request, response);
        }

    }

    /**
     * 动态查询指定数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void conditionalShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        //        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;
        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");

        SpecificationMajorInfo specificationMajorInfo = new SpecificationMajorInfo();
        String smiName = group.getString("majorName");
        String smiCode = group.getString("majorCode");
        specificationMajorInfo.setSmiName(smiName);
        specificationMajorInfo.setSmiCode(smiCode);
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<SpecificationMajorInfo> list = specificationMajorInfoService.findSpecificationMajorInfoFuzzy(specificationMajorInfo);
        if (list != null) {
            PageInfo<SpecificationMajorInfo> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);
    }

    /**
     * 修改专修专业状态（逻辑删除）
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void editByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        Integer smiId = group.getInteger("smiId");
        int i = specificationMajorInfoService.updateSpecificationMajorInfoByState(smiId);
        Boolean status;
        String msg;
        if (i > 0) {
            status = true;
            msg = "修改状态成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改状态失败...";
        statusMsg(request, response, status, msg);

    }

    /**
     * 修改专修专业信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        SpecificationMajorInfo specificationMajorInfo = new SpecificationMajorInfo();
//        从group中获取专修专业名称
        String smiName = group.getString("smiName");
//        从group中获取专修专业代号
        String smiCode = group.getString("smiCode");
//        从group中获取专修专业状态
        Integer smiState = group.getInteger("smiState");
        if (smiName == null || smiName.isEmpty() || smiCode == null || smiCode.isEmpty() || smiState == null) {
            err(request, response);
            return;
        }
        specificationMajorInfo.setSmiName(smiName);
        specificationMajorInfo.setSmiCode(smiCode);
        specificationMajorInfo.setSmiState(smiState == 1);
        List<SpecificationMajorInfo> list = specificationMajorInfoService.findSpecificationMajorInfo(specificationMajorInfo);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "查找出与修改数据有相符的，请修改成正确信息...";
            statusMsg(request, response, status, msg);
            return;
        }
        specificationMajorInfo.setSmiId(group.getInteger("smiId"));
        int i = specificationMajorInfoService.updateSpecificationMajorInfo(specificationMajorInfo);
        if (i > 0) {
            status = true;
            msg = "修改信息成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改信息失败...";
        statusMsg(request, response, status, msg);

    }

    /**
     * 添加专修专业数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        SpecificationMajorInfo specificationMajorInfo = new SpecificationMajorInfo();
//        从group中获取传输过来的专修专业名称
        String smiName = group.getString("smiName");
//        从group中获取传输过来的专修专业代号
        String smiCode = group.getString("smiCode");
        if (smiName == null || smiName.isEmpty() || smiCode == null || smiCode.isEmpty()) {
            err(request, response);
            return;
        }
        specificationMajorInfo.setSmiName(smiName);
        specificationMajorInfo.setSmiCode(smiCode);
//        判断是否有重复的专修专业信息（根据专修专业名称和代号），有就退出
        List<SpecificationMajorInfo> list = specificationMajorInfoService.findSpecificationMajorInfo(specificationMajorInfo);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "添加数据已存在...";
            statusMsg(request, response, status, msg);
            return;
        }
        int i = specificationMajorInfoService.addSpecificationMajorInfo(specificationMajorInfo);
        if (i > 0) {
            status = true;
            msg = "添加数据成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "添加数据失败...";
        statusMsg(request, response, status, msg);
    }

    /**
     * 显示所有专修专业数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void show(HttpServletRequest request, HttpServletResponse response) throws IOException {

//        当jsonObject为空时
        if (jsonObject == null) {
            err(request, response);
            return;
        }

//        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;

        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<SpecificationMajorInfo> list = specificationMajorInfoService.findAll();
        if (list != null) {
            PageInfo<SpecificationMajorInfo> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);
    }


    private void err(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "传送了无效数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void findNoData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pagination", null);
        map.put("status", false);
        map.put("msg", "无匹配数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void statusMsg(HttpServletRequest request, HttpServletResponse response, Boolean status, String msg) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("msg", msg);
        response.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
